package com.mpdbailey.cleverdicandroid;

import java.util.ArrayList;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.pigdogbay.androidutils.mvp.AdPresenter;
import com.pigdogbay.androidutils.mvp.BackgroundColorPresenter;
import com.pigdogbay.androidutils.mvp.IAdView;
import com.pigdogbay.androidutils.mvp.IBackgroundColorModel;
import com.pigdogbay.androidutils.mvp.IBackgroundColorView;
import com.pigdogbay.androidutils.utils.ActivityUtils;

public class MainActivity extends FragmentActivity implements OnClickListener,
		OnEditorActionListener, IAnagramView, IAdView, IBackgroundColorView, IApplicationView, OnSharedPreferenceChangeListener {
	EditText editQuery;
	ApplicationPresenter _ApplicationPresenter;
	BackgroundColorPresenter _BackgroundColorPresenter;
	AnagramPresenter _AnagramPresenter;
	ResultsFragment _ResultsFragment;
	HintsFragment _HintsFragment;
	Button _btnSearch;
	private ArrayList<String> matchesArray;
	private ArrayAdapter<String> itemAdapter;
	private AppData _AppData;
	private BroadcastReceiver _BroadcastReceiver;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		wireUpControls();
		
		_AppData = new AppData(this);
		_AnagramPresenter = new AnagramPresenter(this);
		_AnagramPresenter.SetFindSubAngrams(_AppData.showSubAnagrams());
		_AnagramPresenter.SetResultLimit(_AppData.getResultsLimit());
		_ApplicationPresenter = new ApplicationPresenter(this,_AppData);
		_ApplicationPresenter.setAnagramPresenter(_AnagramPresenter);
		_ApplicationPresenter.setAdPresenter(new AdPresenter(this,_AppData.createAdModel()));
		_BackgroundColorPresenter = new BackgroundColorPresenter(this,_AppData.createBackgroundColorModel());
		_BackgroundColorPresenter.updateBackground();
		_ApplicationPresenter.initialize();
		PreferenceManager
				.getDefaultSharedPreferences(this)
				.registerOnSharedPreferenceChangeListener(this);
	}
	private void wireUpControls()
	{
		_btnSearch = (Button) findViewById(R.id.btnSearch);
		_btnSearch.setOnClickListener(this);
		editQuery = (EditText) findViewById(R.id.editQuery);
		editQuery.setOnEditorActionListener(this);
		_HintsFragment = new HintsFragment();
		_ResultsFragment = new ResultsFragment();
		ReplaceFragment(_HintsFragment);
		matchesArray = new ArrayList<String>();
		itemAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, matchesArray);
		_ResultsFragment.setListAdapter(itemAdapter);

		_BroadcastReceiver = new NewPurchaseBroadcastReceiver();
		LocalBroadcastManager.getInstance(this).registerReceiver(
				_BroadcastReceiver,
				new IntentFilter(AppPurchases.NEW_PURCHASE_INTENT));
		
	}

	private void ReplaceFragment(Fragment fragment) {
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();
		fragmentTransaction.replace(R.id.fragmentHolder, fragment);
		fragmentTransaction.commit();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			PreferenceManager.getDefaultSharedPreferences(this)
					.unregisterOnSharedPreferenceChangeListener(this);
			LocalBroadcastManager.getInstance(this).unregisterReceiver(
					_BroadcastReceiver);
		}
		catch (Exception e) {
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;
		switch (item.getItemId())
		{
		case (R.id.menu_clear):
			_AnagramPresenter.Clear();
			showKeyboard();
			break;
		case (R.id.menu_about):
			intent = new Intent(this, AboutActivity.class);
			startActivity(intent);
			break;
		case (R.id.menu_help):
			intent = new Intent(this, HelpActivity.class);
			startActivity(intent);
			break;
		case (R.id.menu_settings):
			intent = new Intent(this, SettingsActivity.class);
			startActivity(intent);
			break;
		case (R.id.menu_share):
			shareResults();
		default:
			return false;
		}
		return true;
	}

	public void onClick(View v) {
		ReplaceFragment(_ResultsFragment);
		_ApplicationPresenter.searchButtonPressed();
		try {
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			if (imm != null) {
				imm.hideSoftInputFromWindow(editQuery.getWindowToken(), 0);
			}
		}
		catch (Exception e) {
		}
	}

	public void setStatus(String status, boolean busy) {
		_ResultsFragment.setStatus(status, busy);
	}

	public String getQuery() {
		return this.editQuery.getText().toString();
	}

	public void setQuery(String query) {
		this.editQuery.setText(query);
	}

	public void setError(String msg) {
		editQuery.setError(msg);
	}

	public void addMatch(String match) {
		matchesArray.add(match);
		itemAdapter.notifyDataSetChanged();
	}

	public void clearMatches() {
		matchesArray.clear();
		itemAdapter.notifyDataSetChanged();
	}

	public String getStringResource(int id) {
		return getString(id);
	}

	private void showKeyboard() {
		try {
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			if (imm != null) {
				imm.showSoftInput(editQuery, InputMethodManager.SHOW_IMPLICIT);
			}
		}
		catch (Exception e) {
		}
	}

	public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
		if (arg1 == EditorInfo.IME_ACTION_DONE) {
			onClick(null);
		}
		return false;
	}

	public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
		if (key.equals(getString(R.string.code_pref_use_large_dictionary_key))) {
			_ApplicationPresenter.useLargeDictionarySettingChanged();
		}
		else if (key.equals(getString(R.string.settings_show_subanagrams_pref_key))){
			this._AnagramPresenter.SetFindSubAngrams(_AppData.showSubAnagrams());
		}
		else if (key.equals(getString(R.string.settings_result_limit_pref_key))){
			this._AnagramPresenter.SetResultLimit(_AppData.getResultsLimit());
		}
		else if (key.equals(getString(R.string.code_pref_background_colour))){
			_BackgroundColorPresenter.updateBackground();
		}
		else if (key.equals(getString(R.string.code_pref_unlock_color_pack_key))){
			_BackgroundColorPresenter.updateBackground();
		}
		else if (key.equals(getString(R.string.code_pref_disable_ads_key))){
			_ApplicationPresenter.getAdPresenter().adCheck();
		}
	}

	@Override
	public void showDebugScreen() {
		Intent intent = new Intent(MainActivity.this, DebugActivity.class);
		startActivity(intent);
	}

	private void shareResults() {
		try {
			StringBuilder sbuff = new StringBuilder();
			sbuff.append("CleverDic Query:\n");
			sbuff.append(getQuery());
			sbuff.append("\n\nMatches:\n");
			for (String result : matchesArray) {
				sbuff.append(result);
				sbuff.append('\n');
			}
			sbuff.append('\n');
			sbuff.append(getString(R.string.website));
			ActivityUtils.shareText(this, "CleverDic", sbuff.toString(),
					R.string.share_chooser_title);
		}
		catch (Exception e) {
			Toast.makeText(this, "Unable to share", Toast.LENGTH_SHORT).show();
		}
	}
	private void largeDictionaryPurchased()
	{
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		try
		{
			prefs.unregisterOnSharedPreferenceChangeListener(this);
			_ApplicationPresenter.largeDictionaryPurchased();
		}catch(Exception e){}
		finally{
			prefs.registerOnSharedPreferenceChangeListener(this);
		}
	}

	private class NewPurchaseBroadcastReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String extra = intent.getStringExtra(AppPurchases.EXTRA_PURCHASE_SKU);
			if (AppPurchases.SKU_LARGE_DICTIONARY.equals(extra))
			{
				largeDictionaryPurchased();
			}
		}
	}

	@Override
	public void removeAd() {
		ActivitiesHelper.removeAds(this);
	}

	@Override
	public void showAd() {
		ActivitiesHelper.loadAd(this);
	}

	@Override
	public void showWelcomeScreen() {
		ActivityUtils.showInfoDialog(this, R.string.welcome_title,R.string.welcome_msg);
	}

	@Override
	public void showLoadingDictionary() {
		_btnSearch.setText(MainActivity.this
				.getString(R.string.button_loading));
		_btnSearch.setEnabled(false);
	}

	@Override
	public void showReady() {
		int textId = _ApplicationPresenter.getSearchButtonTextId();
		_btnSearch.setText(MainActivity.this
				.getString(textId));
		_btnSearch.setEnabled(true);
	}

	@Override
	public void showLoadingDictionaryError() {
		setError(getString(R.string.DictionaryLoadError));
	}
	@Override
	public void checkAppRate() {
		new com.pigdogbay.androidutils.apprate.AppRate(this)
				.setMinDaysUntilPrompt(7).setMinLaunchesUntilPrompt(5)
				.init();
	}
	@Override
	public void setBackgroundColor(int id) {
		ActivityUtils.setBackground(this, R.id.rootLayout, id);
	}
	@Override
	public void showPurchaseRequiredWarning() {
		//Do nothing
	}	
}
